package uestc.lj.gulishop.product.service.impl;

import com.alibaba.fastjson.TypeReference;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import uestc.lj.common.utils.PageUtils;
import uestc.lj.common.utils.Query;
import uestc.lj.common.utils.R;
import uestc.lj.gulishop.product.dao.SkuInfoDao;
import uestc.lj.gulishop.product.entity.SkuImagesEntity;
import uestc.lj.gulishop.product.entity.SkuInfoEntity;
import uestc.lj.gulishop.product.entity.SpuInfoDescEntity;
import uestc.lj.gulishop.product.feign.SeckillFeignService;
import uestc.lj.gulishop.product.service.*;
import uestc.lj.gulishop.product.vo.SeckillInfoVO;
import uestc.lj.gulishop.product.vo.SkuItemSaleAttrsVO;
import uestc.lj.gulishop.product.vo.SkuItemVO;
import uestc.lj.gulishop.product.vo.SpuItemAttrGroupVO;

import java.math.BigDecimal;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ThreadPoolExecutor;


@Service("skuInfoService")
public class SkuInfoServiceImpl extends ServiceImpl<SkuInfoDao, SkuInfoEntity> implements SkuInfoService {

    @Autowired
    private SkuImagesService skuImagesService;

    @Autowired
    private SpuInfoDescService spuInfoDescService;

    @Autowired
    private AttrGroupService attrGroupService;

    @Autowired
    private SkuSaleAttrValueService skuSaleAttrValueService;

    @Autowired
    private SeckillFeignService seckillFeignService;

    @Autowired
    private ThreadPoolExecutor threadPoolExecutor;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<SkuInfoEntity> page = this.page(
                new Query<SkuInfoEntity>().getPage(params),
                new QueryWrapper<SkuInfoEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public void saveSkuInfo(SkuInfoEntity skuInfoEntity) {
        baseMapper.insert(skuInfoEntity);
    }

    @Override
    public PageUtils queryPageByCondition(Map<String, Object> params) {
        QueryWrapper<SkuInfoEntity> wrapper = new QueryWrapper<>();

        String key = (String) params.get("key");
        if (!StringUtils.isEmpty(key)) {
            wrapper.and(w -> w.eq("sku_id", key).or().like("sku_name", key));
        }
        String catelogId = (String) params.get("catelogId");
        if (!StringUtils.isEmpty(catelogId) && !"0".equalsIgnoreCase(catelogId)) {
            wrapper.eq("catalog_id", catelogId);
        }
        String brandId = (String) params.get("brandId");
        if (!StringUtils.isEmpty(brandId) && !"0".equalsIgnoreCase(brandId)) {
            wrapper.eq("brand_id", brandId);
        }
        String min = (String) params.get("min");
        if (!StringUtils.isEmpty(min)) {
            wrapper.ge("price", min);
        }
        String max = (String) params.get("max");
        if (!StringUtils.isEmpty(max)) {
            try {
                BigDecimal bigDecimal = new BigDecimal(max);
                if (bigDecimal.compareTo(new BigDecimal("0")) > 0) {
                    wrapper.le("price", max);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        IPage<SkuInfoEntity> page = this.page(new Query<SkuInfoEntity>().getPage(params), wrapper);
        return new PageUtils(page);
    }

    @Override
    public List<SkuInfoEntity> getSkusBySpuId(Long spuId) {
        QueryWrapper<SkuInfoEntity> wrapper = new QueryWrapper<>();
        wrapper.eq("spu_id", spuId);
        return this.list(wrapper);
    }

    @Override
    public SkuItemVO getSkuItem(Long skuId) throws ExecutionException, InterruptedException {
        SkuItemVO skuItemVO = new SkuItemVO();
        CompletableFuture<SkuInfoEntity> infoFuture = CompletableFuture.supplyAsync(() -> {
            // 1.sku基本信息获取 pms_sku_info
            SkuInfoEntity skuInfoEntity = getById(skuId);
            skuItemVO.setSkuInfoEntity(skuInfoEntity);
            return skuInfoEntity;
        }, threadPoolExecutor);

        CompletableFuture<Void> saleAttrFuture = infoFuture.thenAcceptAsync(res -> {
            // 3.获取spu的销售属性组合
            List<SkuItemSaleAttrsVO> skuItemSaleAttrsVOS = skuSaleAttrValueService.getSaleAttrsBySpuId(res.getSpuId());
            skuItemVO.setSaleAttr(skuItemSaleAttrsVOS);
        }, threadPoolExecutor);

        CompletableFuture<Void> descFuture = infoFuture.thenAcceptAsync(res -> {
            // 4.获取spu的介绍
            SpuInfoDescEntity spuInfoDescEntity = spuInfoDescService.getById(res.getSpuId());
            skuItemVO.setDesp(spuInfoDescEntity);
        }, threadPoolExecutor);


        CompletableFuture<Void> baseAttrFuture = infoFuture.thenAcceptAsync(res -> {
            // 5.获取spu的规格参数信息
            List<SpuItemAttrGroupVO> spuItemAttrGroupVOS = attrGroupService.getAttrGroupWithAttrsBySpuId(res.getSpuId(),
                    res.getCatalogId());
            skuItemVO.setGroupAttrs(spuItemAttrGroupVOS);
        }, threadPoolExecutor);


        CompletableFuture<Void> imgFuture = CompletableFuture.runAsync(() -> {
            // 2.sku图片信息 pms_sku_images
            List<SkuImagesEntity> imagesEntities = skuImagesService.getImagesBySkuId(skuId);
            skuItemVO.setImages(imagesEntities);
        }, threadPoolExecutor);

        // 6.查询当前商品是否参与秒杀活动
        CompletableFuture<Void> seckillSkuFuture = CompletableFuture.runAsync(() -> {
            R skuSeckillInfo = seckillFeignService.getSkuSeckillInfo(skuId);
            if (skuSeckillInfo.getCode() == 0) {
                List<SeckillInfoVO> seckillInfoVOList = skuSeckillInfo.getData(new TypeReference<List<SeckillInfoVO>>() {
                });
                // 设置当前商品的最近的秒杀活动
                Long recentTime = 9999999999999L;
                Long promotionSessionId = null;
                Long seckillSkuId = null;
                // 寻找当前商品离当前时间最近的秒杀活动场次
                for (SeckillInfoVO seckillInfoVO : seckillInfoVOList) {
                    Long startTime = seckillInfoVO.getStartTime();
                    Long endTime = seckillInfoVO.getEndTime();
                    if (startTime < recentTime && endTime > System.currentTimeMillis()) {
                        recentTime = startTime;
                        promotionSessionId = seckillInfoVO.getPromotionSessionId();
                        seckillSkuId = seckillInfoVO.getSkuId();
                    }
                }
                // 判断最近场次
                for (SeckillInfoVO seckillInfoVO : seckillInfoVOList) {
                    if (seckillInfoVO.getPromotionSessionId().equals(promotionSessionId) && seckillInfoVO.getSkuId().equals(seckillSkuId)) {
                        skuItemVO.setSeckillInfoVO(seckillInfoVO);
                        break;
                    }
                }
            }
        }, threadPoolExecutor);


        CompletableFuture.allOf(saleAttrFuture, descFuture, baseAttrFuture, imgFuture, seckillSkuFuture).get();

        return skuItemVO;
    }

    @Override
    public BigDecimal getNewPrice(Long skuId) {
        SkuInfoEntity skuInfoEntity = baseMapper.selectById(skuId);
        return skuInfoEntity.getPrice();
    }

}